<template>
  <el-container>
    <el-header>
      <h2>AI Agent 聊天测试</h2>
      <el-tabs v-model="activeTab" @tab-click="handleTabClick">
        <el-tab-pane label="简单聊天" name="simple"></el-tab-pane>
        <el-tab-pane label="带提示词聊天" name="prompt"></el-tab-pane>
        <el-tab-pane label="代码生成" name="code"></el-tab-pane>
        <el-tab-pane label="健康检查" name="health"></el-tab-pane>
      </el-tabs>
    </el-header>

    <el-main>
      <!-- 简单聊天 -->
      <div v-if="activeTab === 'simple'">
        <el-card header="简单聊天测试">
          <div class="chat-container">
            <el-scrollbar height="400px">
              <div v-for="msg in simpleChatMessages" :key="msg.id" class="message">
                <el-card :class="msg.type" shadow="never">
                  <div class="message-header">
                    <span class="role">{{ msg.type === 'user' ? '用户' : 'AI助手' }}</span>
                    <span class="time">{{ msg.time }}</span>
                  </div>
                  <div class="message-content">{{ msg.content }}</div>
                  <div v-if="msg.metadata" class="message-metadata">
                    <el-tag size="small">模型: {{ msg.metadata.model }}</el-tag>
                    <el-tag size="small" type="info">Tokens: {{ msg.metadata.tokenCount }}</el-tag>
                  </div>
                </el-card>
              </div>
            </el-scrollbar>
            
            <el-row style="margin-top: 20px;">
              <el-col :span="20">
                <el-input 
                  v-model="simpleMessage" 
                  placeholder="输入消息..." 
                  @keyup.enter="sendSimpleMessage"
                  :disabled="isLoading"
                />
              </el-col>
              <el-col :span="4">
                <el-button 
                  type="primary" 
                  @click="sendSimpleMessage"
                  :loading="isLoading"
                  style="width: 100%;"
                >
                  发送
                </el-button>
              </el-col>
            </el-row>
          </div>
        </el-card>
      </div>

      <!-- 带提示词聊天 -->
      <div v-if="activeTab === 'prompt'">
        <el-card header="带系统提示词聊天">
          <el-form :model="promptForm" label-width="120px">
            <el-form-item label="系统提示词">
              <el-input 
                v-model="promptForm.systemPrompt" 
                type="textarea" 
                :rows="3"
                placeholder="输入系统提示词，例如：你是一个专业的Java开发助手..."
              />
            </el-form-item>
            <el-form-item label="用户消息">
              <el-input 
                v-model="promptForm.message" 
                type="textarea" 
                :rows="2"
                placeholder="输入你的消息..."
              />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="sendPromptMessage" :loading="isLoading">
                发送
              </el-button>
            </el-form-item>
          </el-form>
          
          <el-divider content-position="left">响应结果</el-divider>
          <el-card v-if="promptResponse" shadow="never">
            <div class="response-content">{{ promptResponse.response }}</div>
            <div class="response-metadata">
              <el-tag size="small">模型: {{ promptResponse.model }}</el-tag>
              <el-tag size="small" type="info">Tokens: {{ promptResponse.tokenCount }}</el-tag>
            </div>
          </el-card>
        </el-card>
      </div>

      <!-- 代码生成 -->
      <div v-if="activeTab === 'code'">
        <el-card header="代码生成测试">
          <el-form :model="codeForm" label-width="120px">
            <el-form-item label="编程语言">
              <el-select v-model="codeForm.language" placeholder="选择编程语言">
                <el-option label="Java" value="java"></el-option>
                <el-option label="Python" value="python"></el-option>
                <el-option label="JavaScript" value="javascript"></el-option>
                <el-option label="TypeScript" value="typescript"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="框架">
              <el-input v-model="codeForm.framework" placeholder="例如：Spring Boot, Vue.js, React等" />
            </el-form-item>
            <el-form-item label="需求描述">
              <el-input 
                v-model="codeForm.message" 
                type="textarea" 
                :rows="4"
                placeholder="描述你需要生成的代码功能..."
              />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="sendCodeMessage" :loading="isLoading">
                生成代码
              </el-button>
            </el-form-item>
          </el-form>
          
          <el-divider content-position="left">生成的代码</el-divider>
          <el-card v-if="codeResponse" shadow="never">
            <pre class="code-content">{{ codeResponse.response }}</pre>
            <div class="response-metadata">
              <el-tag size="small">语言: {{ codeResponse.language }}</el-tag>
              <el-tag size="small" type="success">框架: {{ codeResponse.framework || '无' }}</el-tag>
              <el-tag size="small" type="info">Tokens: {{ codeResponse.tokenCount }}</el-tag>
            </div>
          </el-card>
        </el-card>
      </div>

      <!-- 健康检查 -->
      <div v-if="activeTab === 'health'">
        <el-card header="API健康检查">
          <el-button type="primary" @click="checkHealth" :loading="isLoading">
            检查健康状态
          </el-button>
          
          <el-divider content-position="left">检查结果</el-divider>
          <el-card v-if="healthStatus" shadow="never">
            <el-row>
              <el-col :span="12">
                <el-statistic title="服务状态" :value="healthStatus.status">
                  <template #suffix>
                    <el-icon :color="healthStatus.status === 'healthy' ? '#67C23A' : '#F56C6C'">
                      <CircleCheck v-if="healthStatus.status === 'healthy'" />
                      <CircleClose v-else />
                    </el-icon>
                  </template>
                </el-statistic>
              </el-col>
              <el-col :span="12">
                <el-statistic title="AI服务" :value="healthStatus.aiService" />
              </el-col>
            </el-row>
            <div v-if="healthStatus.error" class="error-message">
              <el-alert type="error" :title="healthStatus.error" show-icon />
            </div>
          </el-card>
        </el-card>
      </div>
    </el-main>
  </el-container>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { CircleCheck, CircleClose } from '@element-plus/icons-vue'

const activeTab = ref('simple')
const isLoading = ref(false)

// 简单聊天相关
const simpleMessage = ref('')
const simpleChatMessages = ref([])

// 带提示词聊天相关
const promptForm = reactive({
  systemPrompt: '你是一个友善、专业的AI助手，能够提供准确、有用的信息和建议。',
  message: ''
})
const promptResponse = ref(null)

// 代码生成相关
const codeForm = reactive({
  language: 'java',
  framework: 'Spring Boot',
  message: ''
})
const codeResponse = ref(null)

// 健康检查相关
const healthStatus = ref(null)

// API基础URL
const API_BASE = 'http://localhost:8088/api/chat'

// 发送简单消息
const sendSimpleMessage = async () => {
  if (!simpleMessage.value.trim()) {
    ElMessage.warning('请输入消息')
    return
  }
  
  // 添加用户消息到聊天记录
  const userMsg = {
    id: Date.now(),
    type: 'user',
    content: simpleMessage.value,
    time: new Date().toLocaleTimeString()
  }
  simpleChatMessages.value.push(userMsg)
  
  const messageToSend = simpleMessage.value
  simpleMessage.value = ''
  isLoading.value = true
  
  try {
    const response = await fetch(`${API_BASE}/simple`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({ message: messageToSend })
    })
    
    const data = await response.json()
    
    if (data.success) {
      // 添加AI响应到聊天记录
      const aiMsg = {
        id: Date.now() + 1,
        type: 'assistant',
        content: data.response,
        time: new Date().toLocaleTimeString(),
        metadata: {
          model: data.model,
          tokenCount: data.tokenCount
        }
      }
      simpleChatMessages.value.push(aiMsg)
      ElMessage.success('消息发送成功')
    } else {
      ElMessage.error('发送失败: ' + data.error)
    }
  } catch (error) {
    console.error('发送消息失败:', error)
    ElMessage.error('网络错误: ' + error.message)
  } finally {
    isLoading.value = false
  }
}

// 发送带提示词消息
const sendPromptMessage = async () => {
  if (!promptForm.systemPrompt.trim() || !promptForm.message.trim()) {
    ElMessage.warning('请填写系统提示词和消息')
    return
  }
  
  isLoading.value = true
  
  try {
    const response = await fetch(`${API_BASE}/with-prompt`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        systemPrompt: promptForm.systemPrompt,
        message: promptForm.message
      })
    })
    
    const data = await response.json()
    
    if (data.success) {
      promptResponse.value = data
      ElMessage.success('消息发送成功')
    } else {
      ElMessage.error('发送失败: ' + data.error)
    }
  } catch (error) {
    console.error('发送消息失败:', error)
    ElMessage.error('网络错误: ' + error.message)
  } finally {
    isLoading.value = false
  }
}

// 发送代码生成消息
const sendCodeMessage = async () => {
  if (!codeForm.message.trim()) {
    ElMessage.warning('请输入需求描述')
    return
  }
  
  isLoading.value = true
  
  try {
    const response = await fetch(`${API_BASE}/code`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(codeForm)
    })
    
    const data = await response.json()
    
    if (data.success) {
      codeResponse.value = data
      ElMessage.success('代码生成成功')
    } else {
      ElMessage.error('生成失败: ' + data.error)
    }
  } catch (error) {
    console.error('代码生成失败:', error)
    ElMessage.error('网络错误: ' + error.message)
  } finally {
    isLoading.value = false
  }
}

// 健康检查
const checkHealth = async () => {
  isLoading.value = true
  
  try {
    const response = await fetch(`${API_BASE}/health`)
    const data = await response.json()
    healthStatus.value = data
    
    if (data.status === 'healthy') {
      ElMessage.success('服务健康状态良好')
    } else {
      ElMessage.warning('服务状态异常')
    }
  } catch (error) {
    console.error('健康检查失败:', error)
    ElMessage.error('网络错误: ' + error.message)
    healthStatus.value = {
      status: 'error',
      error: error.message
    }
  } finally {
    isLoading.value = false
  }
}

const handleTabClick = (tab) => {
  console.log('切换到标签页:', tab.name)
}

onMounted(() => {
  console.log('AI聊天测试页面已加载')
})
</script>

<style scoped>
.chat-container {
  max-width: 800px;
  margin: 0 auto;
}

.message {
  margin-bottom: 15px;
}

.message.user {
  text-align: right;
}

.message.assistant {
  text-align: left;
}

.message-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 8px;
  font-size: 12px;
  color: #666;
}

.message-content {
  line-height: 1.6;
  white-space: pre-wrap;
}

.message-metadata {
  margin-top: 10px;
}

.message-metadata .el-tag {
  margin-right: 8px;
}

.response-content {
  line-height: 1.6;
  white-space: pre-wrap;
  margin-bottom: 15px;
}

.response-metadata {
  border-top: 1px solid #eee;
  padding-top: 10px;
}

.response-metadata .el-tag {
  margin-right: 8px;
}

.code-content {
  background-color: #f5f5f5;
  padding: 15px;
  border-radius: 4px;
  overflow-x: auto;
  white-space: pre-wrap;
  font-family: 'Monaco', 'Consolas', 'Courier New', monospace;
  line-height: 1.4;
  margin-bottom: 15px;
}

.error-message {
  margin-top: 15px;
}

.el-header {
  background-color: #f8f9fa;
  border-bottom: 1px solid #e9ecef;
}

.el-main {
  padding: 20px;
}
</style>